package com.itheima.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.book.interceptor.BaseContext;
import com.itheima.book.mapper.MessageMapper;
import com.itheima.book.pojo.dto.MessagePageQueryDTO;
import com.itheima.book.pojo.entity.Message;
import com.itheima.book.pojo.entity.User;
import com.itheima.book.service.MessageService;
import com.itheima.book.service.UserService;
import com.itheima.book.utils.result.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private UserService userService;

    @Override
    public PageResult getMessageList(MessagePageQueryDTO messagePageQueryDTO) {
        // 创建分页对象
        Page<Message> page = Page.of(messagePageQueryDTO.getCurrentPage(), messagePageQueryDTO.getPageSize());
        
        // 构建查询条件
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        // 查询当前用户和指定联系人之间的消息
        wrapper.and(w -> w.eq(Message::getSenderId, BaseContext.getCurrentId())
                         .eq(Message::getReceiverId, messagePageQueryDTO.getContactId())
                         .or()
                         .eq(Message::getSenderId, messagePageQueryDTO.getContactId())
                         .eq(Message::getReceiverId, BaseContext.getCurrentId()));
        
        // 如果指定了消息状态，添加状态条件
        if (messagePageQueryDTO.getStatus() != null) {
            wrapper.eq(Message::getIsRead, messagePageQueryDTO.getStatus() == 1);
        }
        
        // 按创建时间正序排序（从早到晚）
        wrapper.orderByAsc(Message::getCreateTime);
        
        // 执行查询
        Page<Message> messagePage = this.page(page, wrapper);
        
        // 封装返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(messagePage.getTotal());
        pageResult.setRecords(messagePage.getRecords());
        
        return pageResult;
    }

    @Override
    public void sendMessage(Message message) {
        message.setCreateTime(new Date());
        message.setIsRead(false); // 设置消息状态为未读
        message.setSenderId(BaseContext.getCurrentId()); // 设置发送者ID为当前登录用户
        this.save(message);
    }

    @Override
    public void markAsRead(Long messageId) {
        Message message = new Message();
        message.setId(messageId);
        message.setIsRead(true); // 设置消息状态为已读
        this.updateById(message);
    }

    @Override
    public Integer getUnreadCount() {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Message::getReceiverId, BaseContext.getCurrentId())
               .eq(Message::getIsRead, false); // 查询未读消息
        return Math.toIntExact(this.count(wrapper));
    }

    @Override
    public List<Map<String, Object>> getContacts() {
        // 获取当前用户ID
        Long currentUserId = BaseContext.getCurrentId();
        
        // 查询与当前用户有消息往来的所有用户
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w.eq(Message::getSenderId, currentUserId)
                         .or()
                         .eq(Message::getReceiverId, currentUserId))
               .orderByDesc(Message::getCreateTime);
        
        List<Message> messages = this.list(wrapper);
        
        // 使用Set去重，避免重复联系人
        Set<Long> contactIds = new HashSet<>();
        List<Map<String, Object>> contacts = new ArrayList<>();
        
        for (Message message : messages) {
            Long contactId = message.getSenderId().equals(currentUserId) ? 
                           message.getReceiverId() : message.getSenderId();
            
            if (!contactIds.contains(contactId)) {
                contactIds.add(contactId);
                
                // 查询联系人的未读消息数量
                LambdaQueryWrapper<Message> unreadWrapper = new LambdaQueryWrapper<>();
                unreadWrapper.eq(Message::getSenderId, contactId)
                           .eq(Message::getReceiverId, currentUserId)
                           .eq(Message::getIsRead, false);
                int unreadCount = Math.toIntExact(this.count(unreadWrapper));
                
                // 获取联系人信息
                User contact = userService.getById(contactId);
                if (contact != null) {
                    Map<String, Object> contactInfo = new HashMap<>();
                    contactInfo.put("id", contact.getId());
                    contactInfo.put("name", contact.getUsername());
                    contactInfo.put("unread", unreadCount);
                    contactInfo.put("lastMessage", message.getContent());
                    contacts.add(contactInfo);
                }
            }
        }
        
        return contacts;
    }
} 